package com.example.rwq_test.aqs;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * TODO note
 *
 * @author renweiqiang
 * @version 1.0.0
 * @createTime 2024/3/28
 */
@Slf4j
public class SemaphoreDemo {
    /**
     * 工人数
     */
    public static final int N = 8;
    /**
     * 机器数
     */
    public static final int M = 3;

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(M);

        for (int i = 0; i < N; i++) {
            new Worker(i, i % 3 + 1, semaphore).start();
        }
    }

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    static class Worker extends Thread {
        /**
         * 工人No
         */
        private int no;
        /**
         * 工人效率
         */
        private int speed;
        /**
         * 信号量
         */
        private Semaphore semaphore;

        @Override
        public void run() {
            try {
                semaphore.acquire();
                log.info("工人No: {} 占用一个机器生产, 大约需要{}s", this.no, this.speed);
                TimeUnit.SECONDS.sleep(this.speed);
                log.info("工人No: {} 释放一个机器", this.no);
                semaphore.release();
            } catch (Exception e) {
                log.error("Worker run Exception.", e);
            }
        }
    }
}
